const express = require("express");
const fs = require("fs");

const { login } = require("./modules/login");
const { register } = require("./modules/register");
const getUser = require("./modules/getUser");
const session = require("express-session");
const multer = require("multer");
const _upload = require("./modules/upload");
const setUser = require("./modules/setUser");
const https = require("https"); 
const url = require("url")
const qs = require("querystring");

const upload = multer({ dest: "./upload" });
const cors = require("cors");
const app = express()
app.use(express.static("./upload"));
app.use(express.static("./www"))

app.use(cors())
app.use(express.static("./json"))
app.use(express.static("./js"))

app.get("/getGoods",(req,res,next)=>{

    fs.readFile("./data/data.json","utf-8",(err,data)=>{
        if(err){
            res.send(JSON.stringify({
                code:0,
                mag:"数据请求失败",
                data:null
            }))
        }else{
            res.send(JSON.stringify({
                code:1,
                msg:"数据请求成功",
                data:JSON.parse(data)
            }))
        }
    })
})

app.get("/newlife",(req,res,next)=>{

    fs.readFile("./data/newlife.json","utf-8",(err,data)=>{
        if(err){
            res.send(JSON.stringify({
                code:0,
                mag:"数据请求失败",
                data:null
            }))
        }else{
            res.send(JSON.stringify({
                code:1,
                msg:"数据请求成功",
                data:JSON.parse(data)
            }))
        }
    })
})

app.get("/banner",(req,res,next)=>{

    fs.readFile("./data/banner.json","utf-8",(err,data)=>{
        if(err){
            res.send(JSON.stringify({
                code:0,
                mag:"数据请求失败",
                data:null
            }))
        }else{
            res.send(JSON.stringify({
                code:1,
                msg:"数据请求成功",
                data:JSON.parse(data)
            }))
        }
    })
})

app.get("/getDetail", (req,res,next)=>{
    const Id = req.query.Id;
    fs.readFile("./data/goods.json", "utf-8", (err,data)=>{
        const d = JSON.parse(data);
        let i;
        const flag = d.some((val,idx)=>{
            i = idx;
            return val.Id.toString() === Id;
        })
        if(flag){
            res.send(JSON.stringify({
                code:1,
                msg:"获取成功",
                data:d[i]
            }));
        }else{
            res.send(JSON.stringify({
                code:0,
                msg:"没有对应商品，请检查id是否正确",
                data:null
            }));
        }
    })
})



// 读数据
app.get("/getuserdata", (req, res, next) => {
    let data = fs.readFileSync("./www/js/userdata.json", 'utf-8');
    if (data) {
        res.send(JSON.stringify({
            code: 1,
            msg: "数据请求成功",
            data: JSON.parse(data)
        }))
    }
})

// 修改flag数据
app.get("/ModifyData", (req, res) => {
    console.log("进入修改数据")
    let c = Number(req.query.index);
    let data = fs.readFileSync("./www/js/userdata.json", 'utf-8')
    let arr = JSON.parse(data);
    let t = {};
    for (let i = 0; i < arr.length; i++) {
        arr[i].flag = "F"
        if (i == c) {
            t = arr[i];
            arr[i] = arr[0];
            arr[0] = t;
            arr[i].flag = 'T';
        }
    }
    var new_JSON = JSON.stringify(arr);
    fs.writeFileSync("./www/js/userdata.json", new_JSON)
    console.log("进入修改数据")
})

// 添加数据
app.get("/AddData", (req, res) => {
    console.log(12345545454)
    console.log(req.query, "这是req")
    let reqdata = {};
    reqdata.name = req.query.name;
    reqdata.cell = req.query.phone;
    reqdata.add = {};
    reqdata.add.sheng = req.query.sheng;
    reqdata.add.shi = req.query.shi;
    reqdata.add.xian = req.query.xian;
    reqdata.add.anytail = req.query.any;
    reqdata.tail = "公司"
    reqdata.flag = "F"
    console.log(reqdata)   //要添加的数据
    fs.readFile("./www/js/userdata.json", "utf-8", (err, data) => {
        let arr = JSON.parse(data);   //json 文件里的数据
        arr.push(reqdata)
        fs.writeFile("./www/js/userdata.json", JSON.stringify(arr), 'utf8', function (err) {
            console.log('err', err);
        })
    })
    fs.readFile("./www/js/userdata.json", "utf-8", (err, data) => {
        console.log(data)
    })
})


// 删除数据
app.get("/delData", (req, res) => {
    console.log("进入删除")
    let data = fs.readFileSync("./www/js/userdata.json", 'utf-8')
    let arr = JSON.parse(data);
    let t = {};
    let p = [];
    console.log(req.query, "获取删除信息")
    for (let i = 0; i < arr.length; i++) {
        if (arr[i].name == req.query.name && arr[i].cell == req.query.phone && arr[i].add.anytail == req.query.any) {
            console.log("找到了要删除的数据，不进行添加")
        } else {
            t = {};
            console.log(arr[i].name, "t")
            console.log(p, "p")
            t.name = arr[i].name;
            t.cell = arr[i].cell;
            t.add = {};
            t.add.sheng = arr[i].add.sheng;
            t.add.shi = arr[i].add.shi;
            t.add.xian = arr[i].add.xian;
            t.add.anytail = arr[i].add.anytail
            t.tail = "公司"
            t.flag = "F";
            p.push(t)
        }
    }

    console.log(t, "这是t")
    console.log(p, "这是p")
    var new_JSON = JSON.stringify(p);
    fs.writeFileSync("./www/js/userdata.json", new_JSON)
    console.log("删除完毕")
})



app.use(express.urlencoded({extended: false}));

app.use(session({
    secret: '千锋H5',   // 加密信息，可以随便写
    resave: false,     // 强制保存session，默认为true，建议设置为false
    saveUninitialized: true,   // 强制将未初始化的session存储，默认为true，建议为true
    cookie: { maxAge: 1000 * 60 * 30 }    // 过期时间，毫秒数
}));

// 配置cors策略
app.all("*",(req,res,next)=>{
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Methods', 'get,post')
    res.header('Access-Control-Allow-Headers', 'Content-Type')
    next();
})

app.get("/login", login() );

app.post("/register", register() );

app.get("/getUser", getUser() );

app.post("/upload", _upload() );

app.post("/setUser", setUser() );

// jsonp测试接口
app.get("/jsonp", (req,res,next)=>{
    // 从数据库中获取到一段数据...
    const data = "这是来自后端从数据库中获取到的数据";
    res.send(`
        const ahsj = "${data}";
    `);
} );

// jsonp接口
app.get("/getJsonp", (req,res,next)=>{
    // 从数据库中获取到一段数据...
    const obj = {
        code:1,
        msg:"请求成功，数据在data属性内",
        data: "这是来自后端从数据库中获取到的数据"
    }

    res.send(`
        ${req.query.cb}('${JSON.stringify(obj)}');
    `);
} );



app.listen(3000);